import { defineConfig } from 'vite';
import { fileURLToPath, URL } from 'url';
import { ElementPlusResolver } from 'unplugin-vue-components/resolvers';
import vue from '@vitejs/plugin-vue';
import AutoImport from 'unplugin-auto-import/vite';
import Components from 'unplugin-vue-components/vite';
import { visualizer } from 'rollup-plugin-visualizer';
import viteCompression from 'vite-plugin-compression';
import vueJsx from '@vitejs/plugin-vue-jsx';
import vueDevTools from 'vite-plugin-vue-devtools';

// https://vitejs.dev/config/
export default defineConfig(({ mode }) => {
  return {
    resolve: {
      alias: {
        '@': fileURLToPath(new URL('./src', import.meta.url)),
      },
    },
    optimizeDeps: {
      include: ['@ant-design/icons-vue', 'ant-design-vue'],
    },
    plugins: [
      vue(),
      vueJsx(),
      vueDevTools(),
      process.env.npm_lifecycle_event === 'report'
        ? visualizer({ open: true, brotliSize: true, filename: 'report.html' })
        : null,
      viteCompression({
        threshold: 1024000, // 对大于 1mb 的文件进行压缩
      }),
      AutoImport({
        dts: 'src/types/auto-imports.d.ts',
        imports: ['vue', 'vue-router', '@vueuse/core'],
        eslintrc: {
          enabled: true,
          filepath: 'src/types/.eslintrc-auto-import.json',
          globalsPropValue: true,
        },
        resolvers: [ElementPlusResolver()],
      }),
      Components({
        dts: 'src/types/components.d.ts',
        deep: true,
        dirs: ['src/components'],
        extensions: ['vue', 'tsx'],
        resolvers: [ElementPlusResolver()],
      }),
    ],
    server: {
      open: true,
      proxy: {
        '/api': {
          target: 'http://127.0.0.1:8080',
          changeOrigin: true,
          rewrite: (path: string) => path.replace(/^\/api/, ''),
        },
      },
    },
    esbuild: {
      drop: mode === 'production' ? ['console', 'debugger'] : [], // 删除所有的 console 和 debugger
    },
    build: {
      chunkSizeWarningLimit: 1500,
      rollupOptions: {
        output: {
          // 每个 node_modules 模块分成一个 js 文件
          manualChunks: (id: string) => {
            if (id.includes('node_modules')) {
              return id.toString().split('node_modules/')[1].split('/')[1].toString();
            }
          },
          // 用于从入口点创建的块的打包输出格式 [name] 表示文件名,[hash] 表示该文件内容 hash 值
          entryFileNames: 'assets/js/[name].[hash].js', // 用于命名代码拆分时创建的共享块的输出命名
          chunkFileNames: 'assets/js/[name].[hash].js', // 用于输出静态资源的命名，[ext] 表示文件扩展名
          assetFileNames: 'assets/[ext]/[name].[hash].[ext]',
        },
      },
    },
  };
});
